import Icon from '@/components/Icon'
import NavBar from '@/components/NavBar'
import { useHistory, useParams } from 'react-router'
import { useEffect, useState, useRef } from 'react'
import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import {
  getArticleDetail,
  getCommentList,
  getMoreCommentList,
  followUser,
} from '@/store/actions/article'
import { RootState } from '@/store'
import classNames from 'classnames'
import dayjs from 'dayjs'
import DOMPurify from 'dompurify'
import hljs from 'highlight.js'
// highlightElement(DOM) 就可以让代码高亮
import 'highlight.js/styles/monokai.css'
import throttle from 'lodash/throttle'
import NoComment from './components/NoComment'
import CommentItem from './components/CommentItem'

// 导入高亮的语言包
import 'highlight.js/lib/common'
import { InfiniteScroll, Toast } from 'antd-mobile-v5'
import CommentFooter from './components/CommentFooter'
import Share from './components/Share'
import { Drawer } from 'antd-mobile'
import CommentInput from './components/CommentInput/idnex'

const Article = () => {
  const history = useHistory()
  const { id } = useParams<{ id: string }>()
  // console.log(id)
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(getArticleDetail(id))
  }, [dispatch, id])

  const { detail, comment } = useSelector((state: RootState) => state.article)

  useEffect(() => {
    // 配置 highlight.js
    hljs.configure({
      // 忽略未经转义的 HTML 字符
      ignoreUnescapedHTML: true,
    })
    // 获取到内容中所有的code标签
    const codes = document.querySelectorAll('.dg-html pre > code')
    codes.forEach((el) => {
      // 让code进行高亮
      hljs.highlightElement(el as HTMLElement)
    })
  }, [detail])

  // 是否显示顶部信息
  const [isShowAuthor, setIsShowAuthor] = useState(false)
  const authorRef = useRef<HTMLDivElement>(null)
  useEffect(() => {
    const onScroll = throttle(function () {
      const rect = authorRef.current?.getBoundingClientRect()!
      console.log(rect)
      if (rect.top <= 0) {
        setIsShowAuthor(true)
      } else {
        setIsShowAuthor(false)
      }
    }, 300)

    document.addEventListener('scroll', onScroll)
    return () => {
      document.removeEventListener('scroll', onScroll)
    }
  }, [])

  // 发送请求-获取评论数据
  useEffect(() => {
    dispatch(getCommentList(id))
  }, [dispatch, id])

  //加载更多ping'l
  const hasMore = comment.last_id !== comment.end_id
  const loadMore = async () => {
    await dispatch(getMoreCommentList(id, comment.last_id))
  }

  const onFollowUser = async () => {
    await dispatch(followUser(detail.aut_id, detail.is_followed))
    Toast.show('操作成功')
  }

  const commentRef = useRef<HTMLDivElement>(null)
  const isShowComment = useRef(false)
  const goComment = () => {
    if (isShowComment.current) {
      window.scrollTo(0, 0)
    } else {
      window.scrollTo(0, commentRef.current!.offsetTop)
    }
    isShowComment.current = !isShowComment.current
  }
  const [share, setShare] = useState(false)
  const onCloseShare = () => {
    setShare(false)
  }

  // 添加评论的显示和隐藏
  const [showComment, setShowComment] = useState({
    visible: false,
  })
  const closeComment = () => {
    setShowComment({
      visible: false,
    })
  }

  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        {/* 顶部导航栏 */}
        <NavBar
          className="navBar"
          onLeftClick={() => history.go(-1)}
          extra={
            <span>
              <Icon type="icongengduo" />
            </span>
          }
        >
          {isShowAuthor ? (
            <div className="nav-author">
              <img src={detail.aut_photo} alt="" />
              <span className="name">{detail.aut_name}</span>
              <span
                className={classNames(
                  'follow',
                  detail.is_followed ? 'followed' : ''
                )}
                onClick={onFollowUser}
              >
                {detail.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          ) : (
            ''
          )}
        </NavBar>

        <>
          <div className="wrapper">
            <div className="article-wrapper">
              {/* 文章描述信息栏 */}
              <div className="header">
                <h1 className="title">{detail.title}</h1>

                <div className="info">
                  <span>{detail.pubdate}</span>
                  <span>{detail.read_count} 阅读</span>
                  <span>{detail.comm_count} 评论</span>
                </div>

                <div className="author" ref={authorRef}>
                  <img src={detail.aut_photo} alt="" />
                  <span className="name">{detail.aut_name}</span>
                  <span
                    className={classNames('follow', {
                      followed: detail.is_followed,
                    })}
                    onClick={onFollowUser}
                  >
                    {detail.is_followed ? '已关注' : '关注'}
                  </span>
                </div>
              </div>

              {/* 文章正文内容区域 */}
              <div className="content">
                <div
                  className="content-html dg-html"
                  dangerouslySetInnerHTML={{
                    __html: DOMPurify.sanitize(detail.content),
                  }}
                ></div>
                <div className="date">
                  发布文章时间：{dayjs(detail.pubdate).format('YYYY-MM-DD')}
                </div>
              </div>
            </div>
            <div className="comment">
              {/* 评论总览信息 */}
              <div className="comment-header" ref={commentRef}>
                <span>全部评论（{detail.comm_count}）</span>
                <span>{detail.like_count} 点赞</span>
              </div>
              {/* 评论列表 */}
              {detail.comm_count === 0 ? (
                <NoComment></NoComment>
              ) : (
                comment.results?.map((item) => (
                  <CommentItem key={item.com_id} comment={item}></CommentItem>
                ))
              )}
              <InfiniteScroll
                hasMore={hasMore}
                loadMore={loadMore}
              ></InfiniteScroll>
            </div>
          </div>
        </>
        <CommentFooter
          goComment={goComment}
          onShare={() => setShare(true)}
          onComment={() =>
            setShowComment({
              visible: true,
            })
          }
        ></CommentFooter>
      </div>
      {/* 分享抽屉 */}
      <Drawer
        className="drawer-share"
        position="bottom"
        children={''}
        sidebar={<Share onClose={onCloseShare} />}
        open={share}
        onOpenChange={onCloseShare}
      />
      {/* 添加评论的抽屉 */}
      {/* 评论抽屉 */}
      <Drawer
        className="drawer"
        position="bottom"
        children={''}
        sidebar={
          <div className="drawer-sidebar-wrapper">
            {showComment.visible && (
              <CommentInput onClose={closeComment} aritcleId={detail.art_id} />
            )}
          </div>
        }
        open={showComment.visible}
        onOpenChange={closeComment}
      />
    </div>
  )
}

export default Article
